package edu.example.check.servlet;

import com.google.gson.Gson;
import edu.example.Vo.CheckVo;
import edu.example.Vo.UserVo;
import edu.example.check.utils.ReSqlUtils;
import edu.example.common.PowerCheck;
import edu.example.common.ResponseData;
import edu.example.manage.annotation.MyDefineMapper;
import edu.example.manage.utils.JDBCUtils;
import edu.example.pojo.Check;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CheckServlet {
    private static final JDBCUtils jdbcUtils = JDBCUtils.createConnection();
    /**
     * 获取审核列表 (分页功能)
     * @param req
     * @param resp
     */
    @MyDefineMapper("getlist")
    public void getList(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, ServletException {
        // 校验权限
        if (!PowerCheck.isAdmin(req)) {
            req.setAttribute("reMessage", "无权访问");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        // 获取分页信息
        Integer pages = Integer.valueOf(req.getParameter("pages"));
        Integer pageNum = Integer.valueOf(req.getParameter("pageNum"));

        String searchObj = new String(req.getInputStream().readAllBytes());
        Gson gson = new Gson();
        CheckVo selectObj = gson.fromJson(searchObj, CheckVo.class);
        StringBuffer sb = new StringBuffer("select id, type, message, obj_type as objType, execution, obj from `check` where 1 = 1");
        List<Object> params = new ArrayList<>();

        if (selectObj != null) {
            getWhereAndParams(selectObj, sb, params);
        }

        sb.append(" order by type asc");
        sb.append(" limit ?, ?");
        params.add(pages);
        params.add(pageNum);

        List<Check> sourceCheck = (List<Check>) jdbcUtils.queryList(sb.toString(), Check.class, params.toArray());
        resp.getWriter().write(ResponseData.toSuccess(assembleCheckVo(sourceCheck)));
    }

    /**
     * 得到各种查询条件, 手动写动态查询
     * @param selectObj
     * @param sb
     * @param params
     */
    private static void getWhereAndParams(CheckVo selectObj, StringBuffer sb, List<Object> params) {
        if (selectObj.getObjType() != null && !selectObj.getObjType().isBlank()) {
            sb.append(" and obj_type = ?");
            params.add(selectObj.getObjType());
        }
        if (selectObj.getExecution() != null && !selectObj.getExecution().isBlank()) {
            sb.append(" and execution = ?");
            params.add(selectObj.getExecution());
        }
        if (selectObj.getType() != null && !selectObj.getType().isBlank()) {
            sb.append(" and type = ?");
            params.add(selectObj.getType());
        }
    }

    /**
     * 转化审核表列表
     * @param checkList
     * @return 转换后的列表
     */
    private List<CheckVo> assembleCheckVo(List<Check> checkList) {
        List<CheckVo> checkVoList = new ArrayList<>();
        for (Check check : checkList) {
            checkVoList.add(assembleCheck(check));
        }
        return checkVoList;
    }

    /**
     * 转换审核表
     * @param check
     * @return
     */
    private CheckVo assembleCheck(Check check) {
        CheckVo checkVo = new CheckVo();

        checkVo.setId(check.getId());

        switch (check.getType()) {
            case 0:
                checkVo.setType("待审核");
                break;
            case 1:
                checkVo.setType("已审核");
                break;
            case 2:
                checkVo.setType("不通过");
                break;
        }

        switch (check.getExecution()) {
            case 0:
                checkVo.setExecution("删除");
                break;
            case 1:
                checkVo.setExecution("修改");
                break;
            case 2:
                checkVo.setExecution("添加");
                break;
        }

        switch (check.getObjType()) {
            case 0:
                checkVo.setObjType("用户");
                break;
            case 1:
                checkVo.setObjType("楼宇");
                break;
        }

        checkVo.setMessage(check.getMessage());
        return checkVo;
    }

    /**
     * 将审核打入冷宫
     * @param req
     * @param resp
     * @throws SQLException
     * @throws IOException
     */
    @MyDefineMapper("filed")
    public void filed(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, ServletException {
        // 校验权限
        if (!PowerCheck.isAdmin(req)) {
            req.setAttribute("reMessage", "无权访问");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        String id = req.getParameter("id");
        int successRows = jdbcUtils.update("update `check` set type = 2 where id = ?", id);
        resp.getWriter().write(successRows > 0 ? ResponseData.toSuccess("成功") : ResponseData.toError("失败"));
    }

    /**
     * 执行代码
     * @param req
     * @param resp
     * @throws SQLException
     * @throws IOException
     * @throws NoSuchFieldException
     */
    @MyDefineMapper("success")
    public void success(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, NoSuchFieldException, ServletException {
        // 校验权限
        if (!PowerCheck.isAdmin(req)) {
            req.setAttribute("reMessage", "无权访问");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        // 查询出对应的审核信息
        String id = req.getParameter("id");
        Check query = (Check) jdbcUtils.query("select id, type, message, obj_type as objType, execution, obj from `check` where id = ?", Check.class, id);

        // 通过审核信息执行对应的操作
        List<Object> params = new ArrayList<>();
        String sql = "";
        Gson gson = new Gson();
        // 得到执行的方法
        switch (query.getExecution()*10 + query.getObjType()) {
            case 0: // 删除SQL
                sql = ReSqlUtils.deleteUser();
                params.add(query.getObj());
                break;
            case 1:
                sql = ReSqlUtils.deleteBuilds();
                params.add(query.getObj());
                break;
            case 10: {
                sql = ReSqlUtils.updateUser();
                UserVo users = gson.fromJson(query.getMessage(), UserVo.class);
                // 按顺序更新
                params.add(users.getName());
                params.add(users.getGender());
                params.add(users.getPassword());
                params.add(users.getPhone());
                params.add(users.getRole());
                params.add(query.getObj());
                break;
            }
            case 20: {
                sql = ReSqlUtils.insertUser();
                UserVo users = gson.fromJson(query.getMessage(), UserVo.class);
                // 按顺序插入
                params.add(users.getStucode());
                params.add(users.getName());
                params.add(users.getGender());
                params.add(users.getPassword());
                params.add(users.getPhone());
                params.add(users.getRoomsCard());
                params.add(users.getBuildingsCard());
                break;
            }
        }

        int update = jdbcUtils.update(sql, params.toArray());
        // 记录成功
        jdbcUtils.update("update `check` set type = 1 where id = ?", id);
        resp.getWriter().write(update > 0 ? ResponseData.toSuccess("成功") : ResponseData.toError("失败"));
    }
}
